#!/bin/bash

# 最小化本地开发环境设置 - 仅启动应用服务
set -e

echo "🚀 最小化开发环境设置"
echo "======================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 检查Node.js
check_node() {
    log_info "检查 Node.js..."
    
    if ! command -v node > /dev/null; then
        log_error "Node.js 未安装，请先安装 Node.js 18+"
        exit 1
    fi
    
    log_success "Node.js 版本: $(node --version)"
    log_success "npm 版本: $(npm --version)"
}

# 创建模拟数据库配置
create_mock_env() {
    log_info "创建开发环境配置..."
    
    # 后端环境配置 - 使用内存数据库
    cat > ./backend/.env << 'EOF'
NODE_ENV=development
PORT=8000

# 使用内存数据库进行开发测试
MONGODB_URI=memory://localhost/devops-smartbot
REDIS_URL=memory://localhost

# JWT配置
JWT_SECRET=development-secret-key-for-testing-only
JWT_EXPIRES_IN=7d

# OpenAI配置 (可选)
OPENAI_API_KEY=your-openai-api-key

# 监控配置
PROMETHEUS_URL=http://localhost:9090

# 日志配置
LOG_LEVEL=debug
LOG_FILE_PATH=./logs

# 开发模式标志
USE_MEMORY_DB=true
MOCK_PROMETHEUS=true
EOF

    # 前端环境配置
    cat > ./frontend/.env << 'EOF'
REACT_APP_API_URL=http://localhost:8000/api
REACT_APP_WS_URL=http://localhost:8000
REACT_APP_VERSION=1.0.0
REACT_APP_ENV=development
EOF

    log_success "开发环境配置已创建"
}

# 安装依赖
install_deps() {
    log_info "安装项目依赖..."
    
    # 安装后端依赖
    if [ ! -d "./backend/node_modules" ]; then
        log_info "安装后端依赖..."
        cd backend
        npm install
        cd ..
        log_success "后端依赖安装完成"
    else
        log_info "后端依赖已存在"
    fi
    
    # 安装前端依赖
    if [ ! -d "./frontend/node_modules" ]; then
        log_info "安装前端依赖..."
        cd frontend
        npm install
        cd ..
        log_success "前端依赖安装完成"
    else
        log_info "前端依赖已存在"
    fi
}

# 创建内存数据库模拟器
create_memory_db_mock() {
    log_info "创建数据库模拟器..."
    
    # 创建MongoDB内存模拟
    cat > ./backend/src/utils/memoryDb.js << 'EOF'
// 内存数据库模拟器
class MemoryDB {
    constructor() {
        this.collections = new Map();
        this.connected = false;
    }

    async connect() {
        console.log('📦 连接到内存数据库...');
        this.connected = true;
        
        // 初始化默认数据
        this.collections.set('users', new Map([
            ['admin', {
                _id: 'admin',
                username: 'admin',
                password: '$2b$10$8K1p/a0d.LV9M.5Y4O5Y1.1YJ4Y5O5Y1Y5O5Y1Y5O5Y1Y5O5Y1Y5O', // admin123
                email: 'admin@devops.com',
                role: 'admin',
                permissions: ['read', 'write', 'admin'],
                createdAt: new Date(),
                lastLogin: new Date()
            }]
        ]));
        
        this.collections.set('alerts', new Map());
        this.collections.set('tickets', new Map());
        this.collections.set('knowledge', new Map());
        
        console.log('✅ 内存数据库连接成功');
        return true;
    }

    collection(name) {
        if (!this.collections.has(name)) {
            this.collections.set(name, new Map());
        }
        
        return {
            find: (query = {}) => ({
                toArray: () => Array.from(this.collections.get(name).values())
                    .filter(doc => this.matchQuery(doc, query))
            }),
            findOne: (query) => {
                const docs = Array.from(this.collections.get(name).values());
                return docs.find(doc => this.matchQuery(doc, query));
            },
            insertOne: (doc) => {
                const id = doc._id || Math.random().toString(36);
                doc._id = id;
                this.collections.get(name).set(id, doc);
                return { insertedId: id };
            },
            updateOne: (query, update) => {
                const docs = Array.from(this.collections.get(name).entries());
                const [id, doc] = docs.find(([_, doc]) => this.matchQuery(doc, query)) || [];
                if (doc) {
                    Object.assign(doc, update.$set || update);
                    this.collections.get(name).set(id, doc);
                    return { modifiedCount: 1 };
                }
                return { modifiedCount: 0 };
            },
            deleteOne: (query) => {
                const docs = Array.from(this.collections.get(name).entries());
                const [id] = docs.find(([_, doc]) => this.matchQuery(doc, query)) || [];
                if (id) {
                    this.collections.get(name).delete(id);
                    return { deletedCount: 1 };
                }
                return { deletedCount: 0 };
            }
        };
    }

    matchQuery(doc, query) {
        return Object.entries(query).every(([key, value]) => doc[key] === value);
    }

    async close() {
        console.log('📦 关闭内存数据库连接');
        this.connected = false;
    }
}

// Redis内存模拟
class MemoryRedis {
    constructor() {
        this.store = new Map();
        this.connected = false;
    }

    async connect() {
        console.log('📦 连接到内存Redis...');
        this.connected = true;
        console.log('✅ 内存Redis连接成功');
    }

    async get(key) {
        return this.store.get(key) || null;
    }

    async set(key, value, options = {}) {
        this.store.set(key, value);
        if (options.EX) {
            setTimeout(() => this.store.delete(key), options.EX * 1000);
        }
        return 'OK';
    }

    async del(key) {
        return this.store.delete(key) ? 1 : 0;
    }

    async exists(key) {
        return this.store.has(key) ? 1 : 0;
    }

    async quit() {
        console.log('📦 关闭内存Redis连接');
        this.connected = false;
    }
}

module.exports = { MemoryDB, MemoryRedis };
EOF

    log_success "内存数据库模拟器已创建"
}

# 启动应用
start_apps() {
    log_info "启动应用服务..."
    
    # 创建日志目录
    mkdir -p logs
    
    # 启动后端
    log_info "启动后端服务..."
    cd backend
    npm run dev > ../logs/backend.log 2>&1 &
    BACKEND_PID=$!
    cd ..
    
    echo $BACKEND_PID > .backend.pid
    
    # 等待后端启动
    sleep 5
    
    # 检查后端状态
    if curl -f -s http://localhost:8000/health > /dev/null 2>&1; then
        log_success "后端服务启动成功: http://localhost:8000"
    else
        log_warning "后端服务可能启动失败，请检查日志: tail -f logs/backend.log"
    fi
    
    # 启动前端
    log_info "启动前端服务..."
    cd frontend
    npm run dev > ../logs/frontend.log 2>&1 &
    FRONTEND_PID=$!
    cd ..
    
    echo $FRONTEND_PID > .frontend.pid
    
    log_success "前端服务启动中: http://localhost:3000"
}

# 创建停止脚本
create_stop_script() {
    cat > ./scripts/stop-minimal.sh << 'EOF'
#!/bin/bash

echo "🛑 停止最小化开发环境..."

if [ -f .backend.pid ]; then
    kill $(cat .backend.pid) 2>/dev/null || true
    rm .backend.pid
    echo "✅ 后端服务已停止"
fi

if [ -f .frontend.pid ]; then
    kill $(cat .frontend.pid) 2>/dev/null || true
    rm .frontend.pid
    echo "✅ 前端服务已停止"
fi

echo "🎉 所有服务已停止"
EOF
    chmod +x ./scripts/stop-minimal.sh
}

# 显示状态信息
show_status() {
    echo ""
    echo "🎉 最小化开发环境已启动！"
    echo "============================"
    echo ""
    echo "📱 前端应用:    http://localhost:3000"
    echo "🔧 后端 API:    http://localhost:8000"
    echo "📊 API 文档:    http://localhost:8000/api-docs"
    echo ""
    echo "⚠️  注意: 当前使用内存数据库，数据重启后会丢失"
    echo ""
    echo "📋 管理命令:"
    echo "   查看后端日志: tail -f logs/backend.log"
    echo "   查看前端日志: tail -f logs/frontend.log"
    echo "   停止服务:     ./scripts/stop-minimal.sh"
    echo ""
    echo "🔐 默认登录信息:"
    echo "   用户名: admin"
    echo "   密码:   admin123"
    echo ""
    echo "📚 后续步骤:"
    echo "   1. 打开浏览器访问 http://localhost:3000"
    echo "   2. 使用默认账号登录系统"
    echo "   3. 体验基本功能（数据存储在内存中）"
    echo "   4. 如需持久化存储，请安装 MongoDB 和 Redis"
    echo ""
}

# 主函数
main() {
    check_node
    create_mock_env
    install_deps
    create_memory_db_mock
    start_apps
    create_stop_script
    show_status
}

# 错误处理
trap 'log_error "最小化环境设置失败"' ERR

# 执行主函数
main "$@"